package com.kuqi.controller;

import com.kuqi.config.Result;
import com.kuqi.domain.News;
import com.kuqi.domain.PageVo;
import com.kuqi.domain.User;
import com.kuqi.domain.Vo;
import com.kuqi.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

/**
 * @author:kuqi
 * @createTime:2021/11/16 8:43
 * @description:
 */
@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsService newsService;


    @PostMapping("/save")
    private Result<?> save(@RequestBody News news){
        /**
         * 从session中获取nick_name
         */
        /*HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        String nick_name = user.getNick_name();
        news.setNick_name(nick_name);*/

        /**
         * 自定义日期时间为当前日期时间
         */;
        news.setTime(new Date()); //由于在news实体类中给time属性添加了JsonFormat，会自动转换成对应的格式

        newsService.save(news);
        return Result.success();
    }

    @PutMapping("/update")
    private Result<?> updateNews(@RequestBody News news){
        newsService.updateNews(news);
        return Result.success();
    }

    @DeleteMapping("/delete")
    private Result<?> deleteNewsById(@RequestParam Integer id){
        newsService.deleteNewsById(id);
        return Result.success();
    }

    /**
     *
     * @return
     */
    @GetMapping("/newsList")
    private Result<?> queryNewsList(@RequestParam Integer pageNum,//@RequestParam是springMVC框架注解可用于请求参数与后台参数的不同的绑定，也可以用于参数的初始化
                                    @RequestParam Integer pageSize,
                                    @RequestParam(value = "search") String searchContent){
        /**
         * 封装分页信息
         * pageNum--->当前页数
         * pageSize---->当前页显示的记录数
         * searchContent----->搜索关键字
         */
        PageVo pageVo = new PageVo();
        pageVo.setPageNum(pageNum);
        pageVo.setPageSize(pageSize);
        pageVo.setSearchContent(searchContent);

        Vo<News> newsVo = newsService.getNewsListByPage(pageVo);

        return Result.success(newsVo);
    }



    @GetMapping("/getNew")
    private Result<?> getNew(Integer id){
        News result = newsService.getNewsById(id);
        return Result.success(result);
    }
}
